module manager {

    export class UserManager extends egret.EventDispatcher {

        public static readonly domain: string = "https://2zhuji.cn";
        public static readonly login_key: string = "game_userinfo2";
        public static readonly uv_key: string = "game_tunnel_uv";

        public host: Host = new Host();

        public shareTickets = "";

        public authMask: egret.Sprite;

        public authButton;

        private bagManager: BagManager;
        public new_user = 0;
        private login_callback = null;
        private need_auth = false;
        public constructor() {
            super();
            this.bagManager = new BagManager();
        }

        public getBagManager(): BagManager {
            return this.bagManager;
        }

        public login(callback = null): void {
            if (callback) this.login_callback = callback;
            try {
                if (GameManager.isProduct) {
                    this.getUserInfo();
                    //this.checkUserSession();
                }
            } catch (e) {
                console.log("login error:", e);
            }
        }

        private wxLogin() {
            //先查找服务器有没有用户数据，没有再重新授权
            this.onAuthButtonTap({});
        }

        public showLoginPage() {
            egret.log("限时showLoginPage");
            let that = this;
            if (GameManager.getInstance().getAdManager().isChecking()) {
                return;
            }
            if (this.authButton == null) {
                this.authButton = wx.createUserInfoButton({
                    type: 'text',
                    text: '',
                    style: {
                        left: 0,
                        top: 0,
                        width: SystemManager.info.screenWidth,
                        height: SystemManager.info.screenHeight,
                        lineHeight: 36,
                        backgroundColor: '#00ff0000',
                        color: '#ffffff',
                        textAlign: 'center',
                        fontSize: 16,
                        borderRadius: 4
                    }
                });
            }
            this.authButton.show();
            this.authButton.onTap(function (res) {
                if (res["encryptedData"] && res["iv"]) {
                    that.onAuthButtonTap(res);
                }
            });
        }

        private onAuthButtonTap(res) {
            egret.log("loginNow Res:", res);
            let that = this;
            wx.login({
                success: function (loginRes) {
                    that.loginData.encryptedData = res.encryptedData;
                    that.loginData.iv = res.iv;
                    that.sendSession(loginRes.code);
                },
                fail: function (res) {

                },
                complete: function (res) {

                },
            });
        }

        private checkUserSession() {
            wx.login({
                success: res => {
                    this.checkUserSessionImpl(res.code);
                },
                fail: res => {

                },
                complete: res => {

                },
            });
        }

        private checkUserSessionImpl(code: string): void {
            egret.log("开始检测session状态");
            let that = this;
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            let query = wx.getLaunchOptionsSync().query || {}
            let url = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=Login&a=login&token='
                + manager.GameManager.getInstance().getAppToken()
                + '&code=' + code
                + '&tunnel_id=' + (query["wxa_tunnel"] || "")
                + '&inviter_uid=' + (query["inviter_uid"] || "");
            egret.log("获取session url:", url);
            request.open(url, egret.HttpMethod.GET);
            request.send();
            request.addEventListener(egret.Event.COMPLETE, function (event) {
                let request = <egret.HttpRequest>event.currentTarget;
                let data = JSON.parse(request.response);
                egret.log("获取session状态完成:", data);
                egret.log("manager.GameManager.getInstance().openid:", manager.GameManager.getInstance().openid);
                that.new_user = data.new_user;
                that.host.wecha_id = data.user.wecha_id;
                that.loginData.session_3rd = data.session_3rd;
                let new_user = data.new_user;
                if (!data.userinfo) {
                    //没点击过授权按钮，显示授权登陆页
                    that.showLoginPage();
                    egret.log("没点击过授权按钮，显示授权登陆页");
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostIOError, this);
        }

        public sendSession(code) {
            egret.log("开始获取session状态");
            let that = this;
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            let query = wx.getLaunchOptionsSync().query || {}
            let url = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=Login&a=login&token='
                + manager.GameManager.getInstance().getAppToken()
                + '&code=' + code
                + '&tunnel_id=' + (query["wxa_tunnel"] || "")
                + '&inviter_uid=' + (query["inviter_uid"] || "");
            egret.log("获取session url:", url);
            request.open(url, egret.HttpMethod.GET);
            request.send();
            request.addEventListener(egret.Event.COMPLETE, function (event) {
                let request = <egret.HttpRequest>event.currentTarget;
                let data = JSON.parse(request.response);
                egret.log("获取session状态完成:", data);

                egret.log("manager.GameManager.getInstance().openid:", manager.GameManager.getInstance().openid);

                that.new_user = data.new_user;
                that.host.wecha_id = data.user.wecha_id;
                that.loginData.session_3rd = data.session_3rd;
                that.host.user = data.user;
                manager.GameManager.getInstance().getStatisticManager().statsTunnel();
                if (data.userinfo) {
                    //服务器端 有 用户数据，存到本地
                    that.host.userinfo = data.userinfo;
                    that.host.unionid = data.userinfo.unionid;
                }
                let storeData = {
                    session_3rd: that.loginData.session_3rd,
                    host: that.host
                };
                that.setStore(StatisticsManager.login_key, storeData);
                manager.GameManager.getInstance().syncUserInfo(storeData);
                that.bagManager.getMyBag();
                if (that.authButton) {
                    that.getUserBySession();
                } else {
                    if (that.need_auth && !data.userinfo) {
                        that.showLoginPage();
                    } else if (that.login_callback) {
                        that.login_callback();
                        that.login_callback = null;
                    }
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostIOError, this);
        }

        public loginData: any = {};

        private getUserBySession() {
            egret.log("开始获取用户信息");
            let that = this;
            let request = new egret.HttpRequest();
            let params = {
                session_3rd: this.loginData.session_3rd,
                encrypted: this.loginData.encryptedData,
                iv: this.loginData.iv
            };
            let url = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=Login&a=getunionid'
                + '&encrypted=' + this.loginData.encryptedData;
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(url, egret.HttpMethod.GET);
            request.send(params);
            egret.log("获取用户信息url:", url);
            request.addEventListener(egret.Event.COMPLETE, function (event) {
                let request = <egret.HttpRequest>event.currentTarget;
                let data = JSON.parse(request.response);
                egret.log("获取用户信息完成", data);
                if (data && data.wecha_id) {
                    that.host.userinfo = data;
                    that.host.unionid = data.unionid;
                    let storeData = {
                        session_3rd: that.loginData.session_3rd,
                        host: that.host
                    };
                    that.setStore(StatisticsManager.login_key, storeData);
                    that.authButton.hide();
                    manager.DisplayManager.remove(this.authMask);
                    manager.GameManager.getInstance().syncUserInfo(storeData);
                }
            }, this);
        }

        private getUserInfo(need_auth = false) {
            egret.log("开始从本地恢复用户数据");
            if (need_auth) {
                //进入游戏，必须确认服务器端有userinfo
                this.need_auth = need_auth;
                this.getUserFromRemote();
            } else {
                //只用session_3rd做数据统计
                let data = wx.getStorageSync(StatisticsManager.login_key);
                if (data) {
                    manager.GameManager.getInstance().getStatisticManager().statsTunnel();
                    egret.log("开始从本地恢复用户数据完成 Res:", data);
                    manager.GameManager.getInstance().syncUserInfo(data);
                    this.bagManager.getMyBag();
                    if (data["host"]) {
                        this.host = data["host"];
                    }
                    if (this.login_callback) {
                        this.login_callback();
                        this.login_callback = null;
                    }
                } else {
                    this.getUserFromRemote();
                }
            }
        }

        private getUserFromRemote(){
            var that = this;
            wx.login({
                success: function (loginRes) {
                    that.sendSession(loginRes.code);
                },
                fail: function (res) {},
                complete: function (res) {},
            });
        }

        public setStore(key: string, data: any): void {
            wx.setStorage({
                key: key,
                data: data,
                success: function (res) {
                },
                fail: function (res) {
                },
                complete: function (res) {
                }
            });
        }

        private onLoadComplete(event: egret.Event): void {
            let request = <egret.HttpRequest>event.currentTarget;
            console.log(JSON.parse(request.response));
        }

        private onPostIOError(event: egret.IOErrorEvent): void {
            console.log("post error : " + event);
        }

        private musicEnabled: boolean = true;

        public getMusicEnabled(): boolean {
            return this.musicEnabled;
        }

        public getCoin() {

        }

        public saveCoin(coin, local): void {
            wx.setStorage({
                key: StatisticsManager.coin_key,
                data: coin,
                success: function (res) {
                },
                fail: function (res) {
                },
                complete: function (res) {
                }
            });
            if (!Number(coin)) {
                return;
            }
            if (!local) {
                let request = new egret.HttpRequest();
                request.responseType = egret.HttpResponseType.TEXT;
                request.setRequestHeader("Content-type", "application/json");
                let url = StatisticsManager.domain + "/index.php?g=WxaGame&m=Props&a=update_money&session_3rd=" + this.loginData.session_3rd;
                request.open(url, egret.HttpMethod.POST);
                request.send({
                    diamond: coin
                });
            }
        }

    }

}